import React, { createRef } from 'react';
import { Popover } from 'antd';
import { SketchPicker, ColorResult, RGBColor } from 'react-color';
export type ColorConfigType = string;

function rgba2Obj(rgba = '') {
  // /^((([^0][0-9]+|0)\.([0-9]{1,2}))$)|^(([1-9]+)\.([0-9]{1,2})$)/
  let reg = /rgba\((\d+),(\d+),(\d+),(\d+|([0-9].[0-9]{1,2}))\)/g;
  let rgbaObj: RGBColor = { r: 0, g: 0, b: 0, a: 1 };

  rgba.replace(reg, (_m, r, g, b, a) => {
    rgbaObj = { r, g, b, a };
    return rgba;
  });
  return rgbaObj;
}

//value 初始值传来，onchange item给的回调
interface ColorProps {
  value?: ColorConfigType;
  onChange: (v: ColorConfigType) => void;
}

class colorPicker extends React.Component<ColorProps> {
  state = {
    color: '',
  };
  ref = createRef();
  componentDidMount() {
    this.setState(rgba2Obj(this.props.value));
  }

  handleChange = (color: ColorResult) => {
    this.setState({
      color: color.rgb,
    });
    const nowColor = {
      r: color.rgb.r,
      g: color.rgb.g,
      b: color.rgb.b,
      a: color.rgb.a,
    };
    this.props?.onChange(`rgba(${nowColor.r},${nowColor.g},${nowColor.b},${nowColor.a})`);
  };

  render() {
    return (
      <div ref={this.ref}>
        <Popover
          autoAdjustOverflow
          trigger="click"
          overlayInnerStyle={{ padding: 0 }}
          getPopupContainer={() => this.ref.current as HTMLElement}
          content={<SketchPicker color={this.state.color} onChangeComplete={this.handleChange} />}
        >
          {this.props.children}
        </Popover>
      </div>
    );
  }
}

export default colorPicker;
